package com.scanner.hardware.db.helper;

import android.content.Context;

import com.scanner.bean.MotoBarcode;
import com.scanner.bean.MotoQRBarcode;
import com.scanner.hardware.db.manager.DaoManager;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by 皓然 on 2017/8/20.
 */

public class DaoHelper<T> {
    private DaoManager manager;
    private Class<T> clazz;
    public DaoHelper(Context context) {
        manager = DaoManager.getInstance(context);
    }
    private Class<T> getClazz() {
        if (clazz == null) {//获取泛型的Class对象
            clazz = ((Class<T>) (((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
        }
        return clazz;
    }
    // 插入增加
    public boolean insert(T t) {
        return manager.getDaoSession().insert(t) != -1;
    }
    //插入集合
    public boolean insertList(final List<T> datas) {
        boolean flag = false;
        try {
            manager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (T t : datas) {
                        manager.getDaoSession().insertOrReplace(t);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    //删除
    public boolean delete(T t) {
        try {
            manager.getDaoSession().delete(t);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    // 删除所有
    public boolean deleteAll() {
        try {
            manager.getDaoSession().deleteAll(clazz);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询一维码所有
     * @return
     */
    public List<MotoBarcode> getMotoBars(){
        List<MotoBarcode> motoBarcodes = manager.getDaoSession().getMotoBarcodeDao().loadAll();
        return motoBarcodes;
    }

    public void updateSigCheck(MotoBarcode barcode){
        manager.getDaoSession().getMotoBarcodeDao().update(barcode);
    }
    public void deleteAllSig(){
        manager.getDaoSession().getMotoBarcodeDao().deleteAll();
    }

    public MotoBarcode getMotoBean(String name){
        return manager.getDaoSession().getMotoBarcodeDao().load(name);
    }

    /**
     * 查询所有二维码
     * @return
     */
    public List<MotoQRBarcode> getQRMotoBars(){
        return manager.getDaoSession().getMotoQRBarcodeDao().loadAll();
    }

    public void upDateQRCheck(MotoQRBarcode qrBarcode){
        manager.getDaoSession().getMotoQRBarcodeDao().update(qrBarcode);
    }

    public void deleteAllQR(){
        manager.getDaoSession().getMotoQRBarcodeDao().deleteAll();
    }
    public MotoQRBarcode getQRBean(String name){
        return manager.getDaoSession().getMotoQRBarcodeDao().load(name);
    }


}

